<?php

namespace App\Http\Controllers;

use App\Models\Role;
use App\Models\User;
use App\Models\Company;
use Illuminate\Http\Request;
use Auth;
use Image;
use Validator;
use Hash;

class UsersController extends Controller
{
    public function index()
    {
        $q = User::query();
        if (\request()->get('start')) {
            $q->where('created_at', '>=', \request()->get('start'));
        }
        if (\request()->get('end')) {
            $q->where('created_at', '<=', \request()->get('end'));
        }
        if (\request()->get('username')) {
            $q->where('name', 'like', \request()->get('username'));
        }
        $users = $q->with(['company', 'roles'])->get();
        \request()->flash();
        if (\request()->wantsJson()) {
            return response()->json(['code' => 0, 'msg' => '', 'count' => count($users), 'data' => $users]);
        }
        return view('rbac.users.index', compact('users'));
    }

    public function create()
    {
        $roles = Role::all()->pluck('name', 'id');
        $companies = Company::all()->pluck('name', 'id');
        return view('rbac.users.create', compact('roles', 'companies'));
    }

    public function store(Request $request)
    {
        try {
            if ($request->has('password')) {
                $request['password'] = Hash::make($request->get('password'));
            }
            $user = User::create($request->all());
            $user->roles()->sync($request->get('role_id'));
            $response = [
                'message' => 'User created.',
                'data' => $user->toArray(),
            ];

            if ($request->wantsJson()) {
                return response()->json($response);
            }

            return redirect()->back()->with('message', $response['message']);
        } catch (\Exception $e) {
            if ($request->wantsJson()) {
                return response()->json([
                    'error' => true,
                    'message' => $e->getMessage()
                ]);
            }
            return redirect()->back()->withErrors($e->getMessage())->withInput();
        }
    }

    public function edit($id)
    {
        $user = User::find($id);
        $role_ids = optional($user->roles)->pluck('id');
        $role_ids = $role_ids->toArray();
        $roles = Role::all()->pluck('name', 'id');
        $companies = Company::all()->pluck('name', 'id');
        return view('rbac.users.edit', compact('user', 'roles', 'role_ids', 'companies'));
    }

    public function update(Request $request, $id)
    {
        try {
            $user = User::find($id);
            if ($request->get('dont_modify_pwd')) {
                $user->update($request->except('password'));
            } else {
                $request['password'] = Hash::make($request->get('password'));
                $user->update($request->all());
            }

            $user->roles()->sync($request->get('role_id'));
            $response = [
                'message' => 'user updated.',
                'data'    => $user->toArray(),
            ];
            if ($request->wantsJson()) {
                return response()->json($response);
            }
            return redirect()->back()->with('message', $response['message']);
        } catch (\Exception $e) {
            if ($request->wantsJson()) {
                return response()->json([
                    'error'   => true,
                    'message' => $e->getMessage()
                ]);
            }
            return redirect()->back()->withErrors($e->getMessage())->withInput();
        }
    }

    public function destroy($id)
    {
        $user = User::find($id);
        $deleted = $user->delete();
        $user->roles()->sync([]);
        if (request()->wantsJson()) {
            return response()->json([
                'message' => 'user deleted.',
                'deleted' => $deleted,
            ]);
        }

        return redirect()->back()->with('message', 'user deleted.');
    }

    public function profile()
    {
        return view('profile', ['user' => Auth::user()]);
    }
    public function update_avatar(Request $request)
    {
        if ($request->hasFile('avatar')) {
            $avatar = $request->file('avatar');
            $filename = time() . '.' . $avatar->getClientOriginalExtension();
            Image::make($avatar)->resize(300, 300)->save(public_path('/uploads/avatars/' . $filename));
            $user = Auth::user();
            $user->avatar = $filename;
            $user->save();
            \Toastr::success("头像更新成功");
            return view('profile', ['user' => $user]);
        }
    }
    public function online()
    {
        $users = User::all();
        return view('onlines', ['users' => $users]);
    }

    protected function admin_credential_rules(array $data)
    {
        $validator = Validator::make($data, [
            'current-password' => 'required',
            'password' => 'required|same:password',
            'password_confirmation' => 'required|same:password',
        ]);

        return $validator;
    }

    public function updateCredentials(Request $request)
    {
        if (Auth::Check()) {
            $request_data = $request->All();
            $validator = $this->admin_credential_rules($request_data);
            if ($validator->fails()) {
                return redirect()->back()->withErrors($validator)->withInput();
            } else {
                $current_password = Auth::User()->password;
                if (Hash::check($request_data['current-password'], $current_password)) {
                    $user_id = Auth::User()->id;
                    $obj_user = User::find($user_id);
                    $obj_user->password = Hash::make($request_data['password']);;
                    $obj_user->save();
                    \Toastr::success("密码更新成功");
                    return redirect()->back();
                } else {
                    $error = array('current-password' => '当前密码不正确，更新失败');
                    \Toastr::error('当前密码不正确，更新失败');
                    return redirect()->back()->withErrors($error);
                }
            }
        } else {
            return redirect()->to('/');
        }
    }

    public function updateBasic(Request $request)
    {
        $request_data = $request->All();
        $validator = $this->basic_rules($request_data);
        if ($validator->fails()) {
            return redirect()->back()->with('err', $validator->messages())->withInput();
        } else {
            Auth::user()->update($request_data);
            \Toastr::success("个人信息更新成功");
            return redirect()->back()->with('success', '个人信息已更新');
        }
    }

    protected function basic_rules(array $data)
    {
        $validator = Validator::make($data, [
            'name' => 'required|min:2|max:191',
            'email' => 'required|email',
        ]);
        return $validator;
    }
}
